﻿#ifndef CLASS_FACTORY_H
#define CLASS_FACTORY_H

#include <iostream>
#include <string>
#include <map>
using namespace std;

// 声明函数指针
typedef void* (*create_fun)();
// 声明静态创建方法，类的静态方法，相比全局方法，能够解决重复定义
#define DECLARE_CLASS_FACTORY(name) \
public: \
static inline void* createMySelf(){ \
    name *t = new name; \
    return (t == nullptr)? nullptr:t; \
}

// 注册回调创建函数
#define REGISTER_CLASS_FACTORY(name) \
    ClassFactory::getInstance().registClass((#name), \
       static_cast<create_fun>(name::createMySelf));
// 声明创建工厂单例
#define ObjectFactory ClassFactory::getInstance()

class ClassFactory
{
public:
    ~ClassFactory(){}

    //根据类注册时的名字, 创建类实例, 并返回
    void* MakeObject(std::string name)
    {
        std::map<std::string, create_fun>::iterator it = my_map.find(name);
        if (it == my_map.end())
        {
            return nullptr;
        }

        create_fun fun = it->second;
        if (!fun)
        {
            return nullptr;
        }

        return fun();
    }   

    //注册类名称与指针函数到映射关系
    void registClass(std::string name, create_fun fun)
    {
        my_map[name] = fun;
    }   

    //单例模式
    static ClassFactory& getInstance()
    {
        static ClassFactory fac;
        return fac;
    }   

private:
    ClassFactory(){}  //私有
    std::map<std::string, create_fun> my_map;
}; 


#endif
